/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.client.dispatch.actionhandler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.inject.Inject;
import com.gwtp.investmentadvisor.client.common.AppCache;
import com.gwtp.investmentadvisor.client.common.ServerQuerySuggestOracle;
import com.gwtp.investmentadvisor.shared.action.FinancialSecuritySearch;
import com.gwtp.investmentadvisor.shared.action.FinancialSecuritySearchResult;
import com.gwtp.investmentadvisor.shared.entities.FinancialSecurityView;

/**
 * 
 * @author Sunny Gupta
 *
 */
public class FinancialSecuritySearchActionHandler extends
    AbstractAppCachingClientActionHandler<FinancialSecuritySearch, FinancialSecuritySearchResult> {

  // Set expiration time to 1 week from now
  private static final long EXPIRATION_AMOUNT_IN_MS = 7 * 24 * 60 * 60 * 1000;
  
  @Inject
  public FinancialSecuritySearchActionHandler(AppCache cache) {
    super(FinancialSecuritySearch.class, cache);
  }

  @Override
  protected void postfetch(FinancialSecuritySearch action,
      FinancialSecuritySearchResult result) {
    // Check if result is null
    if (result == null) {
      getAppCache().remove(action);
    } else {
      getAppCache().put(action, result);
    }
  }

  @Override
  protected FinancialSecuritySearchResult prefetch(
      FinancialSecuritySearch action) {
    // Get original search text
    String originalSearchString = action.getSearchText();
    
    // Look for superset search
    String searchText = originalSearchString;
    FinancialSecuritySearchResult superSetResult = null;
    while (searchText.length() >= ServerQuerySuggestOracle.MIN_SEARCH_TEXT_LENGTH) {
      FinancialSecuritySearch newAction = new FinancialSecuritySearch(searchText);
      if ((superSetResult = getFromCache(newAction)) != null) {
        // Found a superset
        break;
      } else {
        // Trim last character
        searchText = searchText.substring(0, searchText.length() - 1);
      }
    }
    
    // Check if result found
    if (superSetResult != null) {
      if (searchText == originalSearchString) {
        // Exact match, no filtering needed
        return superSetResult;
      } else {
        // Filter subset results
        List<FinancialSecurityView> filteredResults = filterSearchResults(superSetResult.getSearchResult(), originalSearchString);
        
        // Cache
        FinancialSecuritySearch newAction = new FinancialSecuritySearch(originalSearchString);
        FinancialSecuritySearchResult result = new FinancialSecuritySearchResult(originalSearchString, filteredResults);
        getAppCache().put(newAction, result);
        
        return result;
      }
    } else {
      // Not found
      return null;
    }
  }
  
  private FinancialSecuritySearchResult getFromCache(
      FinancialSecuritySearch newAction) {
    // Lookup in cache
    FinancialSecuritySearchResult result = (FinancialSecuritySearchResult) getAppCache().get(newAction);
    
    // Check for expiry
    if (result != null) {
      long nowInMs = (new Date()).getTime();
      if (getAppCache().getLastUpateTime(newAction) + EXPIRATION_AMOUNT_IN_MS > nowInMs) {
        result = null;
      }
    }
    
    return result;
  }

  private List<FinancialSecurityView> filterSearchResults(
      List<FinancialSecurityView> searchResult,
      String originalSearchString) {
    List<FinancialSecurityView> filteredList = new ArrayList<FinancialSecurityView>();
    
    // Comparison in lower case
    String originalSearchStringLowerCase = originalSearchString.toLowerCase();
    
    // Iterate
    for (FinancialSecurityView view : searchResult) {
      String name = view.getName().toLowerCase();
      String tickerSymbol = view.getTickerSymbol().toLowerCase();
      if (name.contains(originalSearchStringLowerCase) || 
          tickerSymbol.contains(originalSearchStringLowerCase)) {
        filteredList.add(view);
      }
    }
    
    return filteredList;
  }

}
